package com.bizmda.bizsip.app.client;

import lombok.Getter;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Getter
public class SinkClientProxy<T> implements InvocationHandler, Serializable {

    private final Class<T> mapperInterface;
    private final Map<Method, SinkClientMethod> methodCache;
    private String sinkId;

    public SinkClientProxy(Class<T> mapperInterface, String sinkId) {
        this.mapperInterface = mapperInterface;
        this.methodCache = new HashMap<>();
        this.sinkId = sinkId;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {

            }
        }
        final SinkClientMethod sinkClientMethod = cachedMapperMethod(method);

        return sinkClientMethod.execute(args);
    }

    private SinkClientMethod cachedMapperMethod(Method method) {
        SinkClientMethod sinkClientMethod = methodCache.get(method);
        if (sinkClientMethod == null) {
            sinkClientMethod = new SinkClientMethod(method, this);
            methodCache.put(method, sinkClientMethod);
        }
        return sinkClientMethod;
    }

}
